/**
 * Created by CK on 2017/3/22.
 */

function xhForm(_dom) {
    this.form = _dom;
    /**
     * 渲染表单
     *
     * @returns {xhForm}
     *
     * create by ck 20170627
     * modify by ck 20170701    改变按钮颜色
     */
    this.parse = function(){
        this.form.find('select,textarea,:input:not(:reset,:button:submit)').each(function(){
            $(this).addClass('form-control');
        });
        this.form.find('a,:reset,:button,:submit').each(function(){
            if(this.id == 'bt_form_add' || this.id == 'bt_form_edit') {
                $(this).addClass('btn btn-success');
            }
            else if(this.id == 'bt_form_reset') {
                $(this).addClass('btn btn-danger');
            }
            else {
                $(this).addClass('btn btn-default');
            }
        });
        return this;
    };
    /**
     * 填充数据
     *
     * @returns {xhForm}
     *
     * create by ck 20170627
     * modify by ck 20181016    判断bool值，转化为string
     */
    this.fill = function(_data){
        var $this = this;
        $.each(_data, function(key, value){
            var _dom = $this.form.find('[name$='+ key +']');
            if(!_dom) return true;
            if (value === true) {
                value = 'true';
            } else if (value === false) {
                value = 'false';
            }
            _dom.val(value);
        });
        return $this.triggerRequired();
    };
    /**
     * 异步提交表单
     *
     * @returns {xhForm}
     *
     * create by ck 20170627
     */
    this.submit = function(_url, _data, _callback, _options){
        var $this = this, _formData = $this.form.serialize();
        if (_options === undefined) {
            _options = {};
        }
        if(!$.isEmptyObject(_data)){
            _formData += _formData ? '&' + $.param(_data) : $.param(_data);
        }
        var _timeout = typeof _options === 'number' ? _options : 0;
        if (typeof _options === 'object' && _options.timeout) {
            _timeout = _options.timeout;
        }
        $.ajax({
            url: _url.indexOf('/') === 0 ? _url : baseUrl + _url,
            data: _formData,
            type: 'POST',
            dataType: 'json',
            timeout: _timeout ? _timeout * 1000 : 0,
            complete: function(XMLHttpRequest)
            {
                var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                if(_options.check !== false && xhExtra.checkError(result)) return false;
                if(_options.success && result.msg) window.top.xhTop.showSuccess(result.msg);
                _callback.call(this, result);
            }
        });
        return $this;
    };
    /**
     * 重置表单
     *
     * @returns {xhForm}
     *
     * create by ck 20170627
     */
    this.reset = function(){
        this.form.find(':input:not(:reset,:button:submit)').attr('value','').val('');
        this.form.find('textarea').text('').val('');
        this.form.find('select').prop('selectedIndex', 0);
        return this.triggerRequired();
    };
    /**
     * 绑定必填事件
     *
     * @returns {xhForm}
     *
     * create by ck 20170627
     * modify by ck 20170908
     * modify by dale 20180723 新增 data-must select 选中取消是事件
     */
    this.bindRequired = function(_btnDom) {
        var $this = this;
        $this.form.find(':input[must=true], textarea[must=true]').each(function () {
            if($(this).hasClass('select2-hidden-accessible')){
                var select2Dom = $(this).next().find('.select2-selection');
                select2Dom.addClass($(this).val() ? 'has-success' : 'has-warning');
                if (select2Dom.hasClass('has-success')) {
                    select2Dom.attr('style', 'border-color:#2baab1');
                } else {
                    select2Dom.attr('style', 'border-color:#edbc6c');
                }
            }else {
                $(this).attr('placeholder','必填').parent().addClass($(this).val() ? 'has-success' : 'has-warning');
            }
        }).on('change keyup', function(){
            if($(this).hasClass('select2-hidden-accessible')){
                var select2Dom = $(this).next().find('.select2-selection');
                select2Dom.addClass($(this).val() ? 'has-success' : 'has-warning');
                if($(this).val()) {
                    select2Dom.removeClass('has-warning').addClass('has-success');
                }
                else {
                    select2Dom.removeClass('has-success').addClass('has-warning');
                }
                if (select2Dom.hasClass('has-success')) {
                    select2Dom.attr('style', 'border-color:#2baab1');
                } else {
                    select2Dom.attr('style', 'border-color:#edbc6c');
                }
            }else {
                if($(this).val()) {
                    $(this).parent().removeClass('has-warning').addClass('has-success');
                }
                else {
                    $(this).parent().removeClass('has-success').addClass('has-warning');
                }
            }

            if(_btnDom){
                if($this.form.find('.has-warning').length > 0){
                    _btnDom.addClass('disabled');
                }
                else{
                    _btnDom.removeClass('disabled');
                }
            }
        });
        $this.form.find(':input[data-must], textarea[data-must]').each(function () {
            $(this).addClass($(this).val() ? 'xh-input-success' : 'xh-input-warning');
            if (!$(this).attr('placeholder')) {
                $(this).attr('placeholder','必填')
            }
        }).on('change keyup', function(){
            if($(this).val()) {
                $(this).removeClass('xh-input-warning').addClass('xh-input-success');
            }
            else {
                $(this).removeClass('xh-input-success').addClass('xh-input-warning');
            }
            if(_btnDom){
                if($this.form.find('.xh-input-warning').length > 0){
                    _btnDom.addClass('disabled');
                }
                else{
                    _btnDom.removeClass('disabled');
                }
            }
        });
        return $this.triggerRequired();
    };
    /**
     * 触发必填事件
     *
     * @returns {xhForm}
     *
     * create by ck 20170627
     */
    this.triggerRequired = function() {
        this.form.find(':input[must=true], :input[data-must], textarea[must=true], textarea[data-must]').trigger('change');
        return this;
    }
}